﻿using AspNetCore.Host.Hosting;
using AspNetCore.Host.Routing;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class HttpContextExtensions
    {
        public static Endpoint? GetEndpoint(this HttpContext context)
        {
            var features = context.RequestServices.GetRequiredService<IFeatureCollection>();
            var dataSource = features.Get<EndpointDataSource>();
            if (dataSource == null)
            {
                return null;
            }
            foreach (var item in dataSource.Endpoints)
            {
                HttpMethodAttribute? httpMethod =
                    item.Metadata.FirstOrDefault(a => a is HttpMethodAttribute) as HttpMethodAttribute;
                if (httpMethod == null)
                {
                    continue;
                }
                if (httpMethod.Method != null && httpMethod.Method == context.Request.Method && httpMethod.Template == context.Request.Url)
                {
                    return item;
                }
                if (httpMethod.Method == null && httpMethod.Template == context.Request.Url)
                {
                    return item;
                }
            }
            return null;
        }

        public static void SetEndpoint(this HttpContext context, Endpoint endpoint)
        {
            var features = context.RequestServices.GetRequiredService<IFeatureCollection>();
            var dataSource = features.Get<EndpointDataSource>();
            dataSource?.SetEndpoint(endpoint);
        }
    }
}
